﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using StyleMVVM.Validation;

namespace StyleMVVM.MVC.Validation
{
	public class StyleMVVMValidator : ModelValidator
	{
		private IValidationService validationService;

		public StyleMVVMValidator(IValidationService validationService,
		                          ModelMetadata metadata,
		                          ControllerContext controllerContext)
			: base(metadata, controllerContext)
		{
			this.validationService = validationService;
		}

		public override IEnumerable<ModelValidationResult> Validate(object container)
		{
			List<ModelValidationResult> returnValue = new List<ModelValidationResult>();

			if (container != null)
			{
				IValidationContext context = validationService.GetValidationContext(container, false, true);

				if (context.State != ValidationState.Valid)
				{
					IEnumerable<IValidationRuleResultPart> ruleResults = context.PropertyResults(Metadata.PropertyName);

					if (ruleResults != null)
					{
						foreach (IValidationRuleResultPart validationRuleResultPart in ruleResults)
						{
							if (validationRuleResultPart.State == ValidationState.Invalid ||
							    validationRuleResultPart.State == ValidationState.InvalidRequired)
							{
								returnValue.Add(new ModelValidationResult
									                {
										                MemberName = validationRuleResultPart.PartName,
										                Message = validationRuleResultPart.Message
									                });
							}
						}
					}
				}
			}

			return returnValue;
		}
	}
}